package br.com.winesys.geta.dialog;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Window;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.WindowConstants;

public abstract class BaseDialog {

    private Window owner;
    private String title;
    private Dimension size;
    protected JDialog dialog;

    public BaseDialog(Window owner, String title, Dimension size) {
        this.owner = owner;
        this.title = title;
        this.size = size;
    }

    protected void initGUI() {
        this.createActions();
        this.dialog = new JDialog(this.owner, this.title);
        this.dialog.setPreferredSize(this.size);
        this.dialog.setResizable(false);
        this.dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        this.dialog.setModal(true);
        this.dialog.getContentPane().setLayout(new BorderLayout());

        JMenuBar menuBar = createMenuBar();
        if (menuBar != null) {
            this.dialog.setJMenuBar(menuBar);
        }
        JToolBar toolBar = createToolBar();
        if (toolBar != null) {
            toolBar.setRollover(true);
            this.dialog.getContentPane().add(toolBar, BorderLayout.PAGE_START);
            for (Component component : toolBar.getComponents()) {
                if (component instanceof JButton) {
                    JButton b = (JButton) component;
                    b.setText(b.getAction().getValue(Action.NAME).toString());
                    b.setFocusable(false);
                    b.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
                    b.setOpaque(false);
                }
            }
        }
        JPanel status = createStatus();
        if (status != null) {
            this.dialog.getContentPane().add(status, BorderLayout.PAGE_END);
        }
        JComponent componente = createComponent();
        if (componente != null) {
            this.dialog.getContentPane().add(componente, BorderLayout.CENTER);
        }
        this.dialog.doLayout();
        this.dialog.pack();
        Rectangle windowBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
        this.dialog.setLocation((windowBounds.width - this.dialog.getWidth()) / 2, (windowBounds.height - this.dialog.getHeight()) / 2);
    }

    public void run() {
        this.initGUI();
        this.dialog.setVisible(true);
    }

    protected abstract void createActions();

    protected abstract JToolBar createToolBar();

    protected abstract JMenuBar createMenuBar();

    protected abstract JPanel createStatus();

    protected abstract JComponent createComponent();
}
